package com.supor.md_video.ui;

import android.net.wifi.WifiManager;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.alibaba.fastjson.JSONObject;
import com.android.baseconfig.base.RxBus3;
import com.android.baseconfig.common.utils.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.google.gson.Gson;
import com.supor.aiot.common.app.AppAgent;
import com.supor.aiot.common.app.Constants;
import com.supor.aiot.common.app.SuporApplication;
import com.supor.aiot.common.app.SuporPresenter;
import com.supor.aiot.common.arouter.PathUrl;
import com.supor.aiot.common.base.BaseMVVMActivity;
import com.supor.aiot.common.entity.Result;
import com.supor.aiot.common.helper.GlobalDataCache;
import com.supor.aiot.common.utils.NotNullUtils;
import com.supor.aiot.common.utils.SharePopUtils;
import com.supor.md_video.R;
import com.supor.md_video.adapter.VideoListViewAdapter;
import com.supor.md_video.databinding.ActivityVideoListBinding;
import com.supor.md_video.entity.FavoritStateBean;
import com.supor.md_video.entity.VideoCommListBean;
import com.supor.md_video.entity.VideoItemInfoBean;
import com.supor.md_video.entity.VideoListBean;
import com.supor.md_video.model.VideoListModel;
import com.supor.md_video.tools.NumberUtils;
import com.supor.md_video.tools.VideoListPlayerManager;

import java.util.ArrayList;

import androidx.annotation.NonNull;
import androidx.lifecycle.Observer;
import androidx.viewpager2.widget.ViewPager2;

import io.reactivex.rxjava3.functions.Consumer;

/**
 * @author zook
 */
@Route(path = PathUrl.PATH_MD_VIDEO_LIST)
public class VideoListActivity extends BaseMVVMActivity<VideoListModel, ActivityVideoListBinding> implements OnItemChildClickListener, View.OnClickListener {
    public final static int PAGE_TYPE_SINGLE = 1;
    public final static int PAGE_TYPE_MUTI = 0;

    private int currentPage;
    private VideoListViewAdapter mVideoListViewAdapter;
    private VideoListPlayerManager videoListPlayerManager;
    private VideoCommListDialog mVideoCommListDialog;
    private boolean noMoreData;
    private boolean netNotified;
    private int pageType;
    private boolean startFromRecipeInfo;

    @Override
    protected int resourceId() {
        return R.layout.activity_video_list;
    }

    @Override
    protected void initView() {
        super.initView();
        if (null != getIntent()) {
            pageType = getIntent().getIntExtra("page_tyep", 0);
            startFromRecipeInfo = getIntent().getBooleanExtra("start_from_repice_info", false);
        }
        bindingView.ivPageBack.setOnClickListener(view -> finish());
        bindingView.ivSearch.setOnClickListener(view -> {
            ARouter.getInstance().build(PathUrl.PATH_INTO_SEARCH)
                    .withTransition(com.android.baseconfig.R.anim.activity_open_enter,
                            com.android.baseconfig.R.anim.activity_open_exit)
                    .navigation(VideoListActivity.this);
            SuporApplication.getInstance().mainHandler.postDelayed(()
                    -> {
                VideoListActivity.this.finish();
            }, 300);
        });
    }

    @Override
    protected void initData() {
        super.initData();
        showLoading();
        viewModel.getVideoListResult().observe(this, new Observer<Result<VideoListBean>>() {
            @Override
            public void onChanged(Result<VideoListBean> videoListBeanResult) {
//                finishLoad();
                closeLoading();
                if (null != videoListBeanResult && null != videoListBeanResult.getData()) {
                    mVideoListViewAdapter.addData(videoListBeanResult.getData().getRows());
                    if (videoListBeanResult.getData().getPage() >= videoListBeanResult.getData().getAllpages()) {
                        noMoreData = true;
                    }
                }
//                bindingView.tvLoading.setVisibility(View.GONE);
            }
        });
        viewModel.getFavoritResult().observe(this, new Observer<FavoritStateBean>() {
            @Override
            public void onChanged(FavoritStateBean favoritStateBean) {
                if (null != favoritStateBean
                        && mVideoListViewAdapter.getData().size() > favoritStateBean.getLocalPosition()) {
                    VideoItemInfoBean videoItemInfoBean = mVideoListViewAdapter.getData().get(favoritStateBean.getLocalPosition());
                    if (!videoItemInfoBean.getRecipeId().equals(favoritStateBean.getId())) {
                        return;
                    }
                    videoItemInfoBean.setFavoriteCount(videoItemInfoBean.getFavoriteCount() + favoritStateBean.getLocalCountType());
                    videoItemInfoBean.setFavoriteType(favoritStateBean.getLocalCountType() > 0
                            ? 1 : 2);
                    ImageView ivSub = (ImageView) mVideoListViewAdapter
                            .getViewByPosition(favoritStateBean.getLocalPosition(), R.id.iv_sub);
                    if (null != ivSub) {
                        ivSub.setBackgroundResource(videoItemInfoBean.getFavoriteType() == 1
                                ? R.mipmap.ic_video_list_sub_light : R.mipmap.ic_video_list_sub);
                    }
                    TextView tvSubcount = (TextView) mVideoListViewAdapter
                            .getViewByPosition(favoritStateBean.getLocalPosition(), R.id.tv_sub_num);
                    if (null != tvSubcount) {
                        tvSubcount.setText(NumberUtils.formatNum(videoItemInfoBean.getFavoriteCount()));
                    }
                }
            }
        });

        viewModel.getShareUpdateResult().observe(this, new Observer<Result>() {
            @Override
            public void onChanged(Result result) {
                // todo
            }
        });

        RxBus3.getInstance().register(Constants.TicPecipe.COMM_ADD, new Consumer<VideoCommListBean>() {
            @Override
            public void accept(VideoCommListBean videoCommListBean) throws Throwable {
                if (null != videoCommListBean
                        && mVideoListViewAdapter.getData().size() > videoCommListBean.getLocalPosition()) {
                    VideoItemInfoBean videoItemInfoBean = mVideoListViewAdapter.getData().get(videoCommListBean.getLocalPosition());
                    if (!videoItemInfoBean.getRecipeId().equals(videoCommListBean.getLocalId())) {
                        return;
                    }
                    videoItemInfoBean.setReplyCount(videoItemInfoBean.getReplyCount() + 1);
                    TextView tvSubcount = (TextView) mVideoListViewAdapter
                            .getViewByPosition(videoCommListBean.getLocalPosition(), R.id.tv_comm_num);
                    if (null != tvSubcount) {
                        tvSubcount.setText(NumberUtils.formatNum(videoItemInfoBean.getReplyCount()));
                    }
                }
            }
        });
        RxBus3.getInstance().register(Constants.TicPecipe.TIK_PECIPE_STATE, new Consumer<String>() {
            @Override
            public void accept(String json) throws Throwable {
                int position = videoListPlayerManager.getCurrentViewPosition();

                if (mVideoListViewAdapter.getData().size() > position) {
                    VideoItemInfoBean videoItemInfoBean = mVideoListViewAdapter.getData().get(position);
                    if (null != videoItemInfoBean) {
                        JSONObject jo = JSONObject.parseObject(json);
                        int type = jo.getIntValue(Constants.Key.param_type);
                        String params = jo.getString(Constants.Key.param_params);
                        String id = NotNullUtils.getNotNullValue(JSONObject.parseObject(params).getString("id"));
                        if (id.equals(videoItemInfoBean.getRecipeId())) {
                            switch (type) {//0 无状态|1 添加评论|2 添加食谱收藏|3 取消食谱收藏|4 添加食谱点赞|5 取消食谱点赞
                                case 1:
                                    videoItemInfoBean.setReplyCount(videoItemInfoBean.getReplyCount() + 1);
                                    TextView tvCommCount = (TextView) mVideoListViewAdapter
                                            .getViewByPosition(position, R.id.tv_comm_num);
                                    if (null != tvCommCount) {
                                        tvCommCount.setText(NumberUtils.formatNum(videoItemInfoBean.getReplyCount()));
                                    }
                                    break;
                                case 2:
                                    videoItemInfoBean.setFavoriteCount(videoItemInfoBean.getFavoriteCount() + 1);
                                    videoItemInfoBean.setFavoriteType(1);
                                    ImageView ivSub = (ImageView) mVideoListViewAdapter
                                            .getViewByPosition(position, R.id.iv_sub);
                                    if (null != ivSub) {
                                        ivSub.setBackgroundResource(R.mipmap.ic_video_list_sub_light);
                                    }
                                    TextView tvSubcount = (TextView) mVideoListViewAdapter
                                            .getViewByPosition(position, R.id.tv_sub_num);
                                    if (null != tvSubcount) {
                                        tvSubcount.setText(NumberUtils.formatNum(videoItemInfoBean.getFavoriteCount()));
                                    }
                                    break;
                                case 3:
                                    videoItemInfoBean.setFavoriteCount(videoItemInfoBean.getFavoriteCount() - 1);
                                    videoItemInfoBean.setFavoriteType(2);
                                    ImageView ivUnSub = (ImageView) mVideoListViewAdapter
                                            .getViewByPosition(position, R.id.iv_sub);
                                    if (null != ivUnSub) {
                                        ivUnSub.setBackgroundResource(R.mipmap.ic_video_list_sub);
                                    }
                                    TextView tvUnSubcount = (TextView) mVideoListViewAdapter
                                            .getViewByPosition(position, R.id.tv_sub_num);
                                    if (null != tvUnSubcount) {
                                        tvUnSubcount.setText(NumberUtils.formatNum(videoItemInfoBean.getFavoriteCount()));
                                    }
                                    break;
                                case 4:
                                    break;
                                case 5:
                                    break;
                                default:
                                    break;

                            }
                        }
                    }
                }
            }
        });
        viewModel.getShareUpdateResult().observe(this, new Observer<Result>() {
            @Override
            public void onChanged(Result result) {
                if (result instanceof Result.Success) {
                    if (mVideoListViewAdapter.getData().size() > videoListPlayerManager.getCurrentViewPosition()) {
                        VideoItemInfoBean videoItemInfoBean = mVideoListViewAdapter.getData().get(videoListPlayerManager.getCurrentViewPosition());
                        if (null != videoItemInfoBean) {
                            videoItemInfoBean.setShareCount(videoItemInfoBean.getShareCount() + 1);
                            TextView tvShareCount = (TextView) mVideoListViewAdapter
                                    .getViewByPosition(videoListPlayerManager.getCurrentViewPosition(), R.id.tv_share_num);
                            if (null != tvShareCount) {
                                tvShareCount.setText(NumberUtils.formatNum(videoItemInfoBean.getShareCount()));
                            }
                        }
                    }
                }
            }
        });
        initVideoViewList();
    }

    private void initVideoViewList() {
        videoListPlayerManager = new VideoListPlayerManager();
        videoListPlayerManager.init(this);

        mVideoListViewAdapter = new VideoListViewAdapter(new ArrayList<>());
        videoListPlayerManager.bindAdapter(mVideoListViewAdapter);
        videoListPlayerManager.bindToolBar(bindingView.llTopContainer);
        mVideoListViewAdapter.setOnItemChildClickListener(this);

        //禁止滚动true为可以滑动false为禁止
        bindingView.vpLiveList.setUserInputEnabled(true);
        //设置垂直滚动ORIENTATION_VERTICAL，横向的为
        bindingView.vpLiveList.setOrientation(ViewPager2.ORIENTATION_VERTICAL);
        bindingView.vpLiveList.setOffscreenPageLimit(2);
        bindingView.vpLiveList.registerOnPageChangeCallback(videoListPlayerManager.getPageChangeCallBack());
        bindingView.vpLiveList.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {

            @Override
            public void onPageSelected(int position) {
                super.onPageSelected(position);
                if (null != mVideoCommListDialog) {
                    mVideoCommListDialog.dismiss();
                }
                mVideoCommListDialog = null;
                if (!noMoreData && !viewModel.inRequest() && position == mVideoListViewAdapter.getData().size() - 5) {
                    viewModel.loadVideoListData(++currentPage, bindDestoryAutoDispose());
                }
            }
        });

        bindingView.vpLiveList.setAdapter(mVideoListViewAdapter);

        if (pageType == PAGE_TYPE_SINGLE) {
            String json = getIntent().getStringExtra("recipe_info");
            VideoItemInfoBean videoItemInfoBean = new Gson().fromJson(json, VideoItemInfoBean.class);
            if (null != videoItemInfoBean) {
                mVideoListViewAdapter.addData(videoItemInfoBean);
                noMoreData = true;
            }
            closeLoading();
        } else {
            viewModel.loadVideoListData(currentPage = 1, bindDestoryAutoDispose());
        }
    }

    @Override
    public void updateWifiStatus(int state) {
        super.updateWifiStatus(state);
        if (state == WifiManager.WIFI_STATE_DISABLING && !netNotified) {
            netNotified = true;
            ToastUtils.getInstance().showToast(this, "当前为非Wi-Fi环境，请注意流量消耗");
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (null != videoListPlayerManager) {
            videoListPlayerManager.onPause();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (null != videoListPlayerManager) {
            videoListPlayerManager.onResume();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        videoListPlayerManager.destoryManager();
        RxBus3.getInstance().unregister(this.getClass());
    }

    @Override
    public void onItemChildClick(@NonNull BaseQuickAdapter adapter, @NonNull View view, int position) {
        if (!passClick() && null == mVideoListViewAdapter || mVideoListViewAdapter.getData().size() <= position) {
            return;
        }
        if (view.getId() == R.id.ll_comm) {
            mVideoCommListDialog = null;
            mVideoCommListDialog = VideoCommListDialog.newInstance(mVideoListViewAdapter.getData()
                    .get(position).getRecipeId(), position);
            mVideoCommListDialog.show(getSupportFragmentManager(), "VideoCommListDialog");
        } else if (view.getId() == R.id.ll_sub) {
            if (AppAgent.isLogin() && null != GlobalDataCache.userInfo) {
                if (mVideoListViewAdapter.getData().get(position).getFavoriteType() == 1) {
                    viewModel.unSubRecipe(mVideoListViewAdapter.getData().get(position).getRecipeId()
                            , position, bindDestoryAutoDispose());
                } else {
                    viewModel.subRecipe(mVideoListViewAdapter.getData().get(position).getRecipeId()
                            , GlobalDataCache.userInfo.getBossUserId()
                            , position
                            , bindDestoryAutoDispose());
                }
            } else {
                SuporPresenter.getInstance().getCmccHelper().displayLogin(false);
            }
        } else if (view.getId() == R.id.iv_jump_recipe) {
            if (startFromRecipeInfo) {
                finish();
            } else {
                VideoItemInfoBean bean = mVideoListViewAdapter.getData().get(position);
                if (AppAgent.h5Debug) {
                    AppAgent.startDebugTiny(this, Constants.App.PAGE_RECIPE, "", "id=" + bean.getRecipeId());
                } else {
                    AppAgent.startRecipePage(bean.getRecipeId(), bean.getModelId());
                }
            }
        } else if (view.getId() == R.id.ll_share) {
            VideoItemInfoBean bean = mVideoListViewAdapter.getData().get(position);
            showShareDialog(bean);
        } else if (view.getId() == R.id.iv_user_ava) {
            ARouter.getInstance()
                    .build(PathUrl.PATH_COOKER_HOME)
                    .withString("CHEF_ID", mVideoListViewAdapter.getData().get(position).getChefId())
                    .withTransition(com.android.baseconfig.R.anim.activity_open_enter,
                            com.android.baseconfig.R.anim.activity_open_exit)
                    .navigation(AppAgent.getCurrentActivity());
        }
    }

    private void showShareDialog(VideoItemInfoBean bean) {
        try {
            // 食谱分享示例

            // 初始化分享弹框
            JSONObject jo = new JSONObject();
            // 分享类型：0取消分享；1微信；2微信朋友圈；3 QQ好友；4 QQ空间；5微博；6支付宝；7抖音
            // jo.put(Constants.Key.param_shareType, 1);
            // 分享方式：0x1-text，0x2-image，0x3-URL
            jo.put(Constants.Key.param_type, 3);
            // 分享标题
            jo.put(Constants.Key.param_title, bean.getRecipeName());
            // 分享内容描述
            jo.put(Constants.Key.param_desc, bean.getRecipeContent());
            // URL连接
            jo.put(Constants.Key.param_path, AppAgent.getRecipeShareUrl() + bean.getRecipeId());
            // 自定义分享预览大图
            jo.put(Constants.Key.param_bgImgUrl, bean.getImageVertical());
            // 视频Url
            jo.put(Constants.Key.param_videoUrl, bean.getHighVertical());

            SharePopUtils.getInstance()
                    .showWechat(true)
                    .showWeibo(true)
                    .showDouyin(true)
                    .setResultCallback(() -> viewModel.shareUpdate(bean.getRecipeId()))
                    .params(jo)
                    .showPop(this, bindingView.getRoot());
            //                    .initPop(this);

            // 弹框显示
            //            SharePopUtils.getInstance().showPop(this, bindingView.getRoot());
        } catch (Exception e) {

        }
    }

    @Override
    public void onClick(View v) {
    }

//    private void setAndroidNativeLightStatusBar(boolean dark) {
//        View decor = getWindow().getDecorView();
//        if (dark) {
//            decor.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
//        } else {
//            decor.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
//        }
//    }
}